package contos.lancamento;

import com.jback.datemanager.DateManager;
import contos.util.HibernateUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author jandir
 */
public class LancamentoManagedBean {

    private Date periodo;

    /** Creates a new instance of LancamentoManagedBean */
    public LancamentoManagedBean() {
    }

    public Date getPeriodo() {
        return periodo;
    }

    public void setPeriodo( Date periodo ) {
        this.periodo = periodo;
    }

    public Collection<Lancamento> getLancamentos() {
        Collection<Lancamento> to_return = new ArrayList<Lancamento>();

        System.out.println( "*** " + periodo );
        if ( periodo == null ) {
            return to_return;
        }

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        try {
            session.beginTransaction();
            List<Object[]> result = session.createSQLQuery(
                    "select id,descricao,valor,id_usuario_sistema,id_usuario_origem,id_usuario_destino,periodo,data_inclusao,tipo " +
                    "   from schema_testes.lancamento where (to_char(data_inclusao,'YYYYMM'))='" +
                    new DateManager().formatDate( periodo, "yyyyMM" ) +
                    "'" ).list();
            for ( Object[] objects : result ) {
                Lancamento l = new Lancamento();
                l.setId( Long.parseLong( objects[0].toString() ) );
                l.setDescricao( objects[1].toString() );
                l.setValor( Double.valueOf( objects[2].toString() ) );
                l.setIdUsuarioSistema( Long.parseLong( objects[3].toString() ) );
                l.setIdUsuarioOrigem( Long.parseLong( objects[4].toString() ) );
                l.setIdUsuarioDestino( Long.parseLong( objects[5].toString() ) );
                l.setPeriodo( Integer.parseInt( objects[6].toString() ) );
                l.setDataInclusao( (Date) objects[7] );
                l.setTipo( objects[8].toString() );
                to_return.add( l );
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        } finally {
            session.flush();
            session.getTransaction().commit();
            session.close();
        }

        return to_return;
    }
}
